package io.github.junxworks.qt.modules.data.utils;

import com.alibaba.fastjson.JSONObject;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @program :springbootdev
 * @description:
 * @author:Junxworks
 * @create:2019-08-16 19:17
 */
public class CommJsonUtils
{
    public static String getJsonObjectString(JSONObject jsonObject, String key, String defVal)
    {
        if (jsonObject == null)
        {
            return defVal;
        }
        if (!jsonObject.containsKey(key))
        {
            return defVal;
        }
        String retVal = jsonObject.getString(key);
        return retVal;
    }

    public static Long getJsonObjectLong(JSONObject jsonObject, String key, Long defVal)
    {
        if (jsonObject == null)
        {
            return defVal;
        }
        if (!jsonObject.containsKey(key))
        {
            return defVal;
        }
        Long retVal = jsonObject.getLong(key);
        return retVal;
    }

    public static BigDecimal getJsonObjectBigDecimal(JSONObject jsonObject, String key, BigDecimal defVal)
    {
        if (jsonObject == null)
        {
            return defVal;
        }
        if (!jsonObject.containsKey(key))
        {
            return defVal;
        }
        BigDecimal retVal = jsonObject.getBigDecimal(key);
        return retVal;
    }

    public static Integer getJsonObjectInteger(JSONObject jsonObject, String key, Integer defVal)
    {
        if (jsonObject == null)
        {
            return defVal;
        }
        if (!jsonObject.containsKey(key))
        {
            return defVal;
        }
        Integer retVal = jsonObject.getInteger(key);
        return retVal;
    }

    public static Date getJsonObjectDate(JSONObject jsonObject, String key, String format, Date defVal)
    {
        if (jsonObject == null)
        {
            return defVal;
        }
        if (!jsonObject.containsKey(key))
        {
            return defVal;
        }
        String dateVal = getJsonObjectString(jsonObject, key, "");
        if ("".equals(dateVal))
        {
            return defVal;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date retDate = null;
        try
        {
            retDate = sdf.parse(dateVal);
        }
        catch(Exception e)
        {
            e.printStackTrace();
            retDate = defVal;
        }
        return retDate;
    }
}
